<?php
/**
 * +-------------------------------------------------------------
 * |Caption:
 * +-------------------------------------------------------------
 * |Author: Lenny
 * +-------------------------------------------------------------
 * |Email:  1685964109@qq.com
 * +-------------------------------------------------------------
 * |Date:   2024/6/18 下午2:22
 * +-------------------------------------------------------------
 */

namespace app\common\middleware;

use app\common\traits\JsonTrait;
use Closure;
use ReflectionClass;

class CheckLogin
{
    use JsonTrait;
    public function handle($request, Closure $next)
    {
        $controller = $request->controller();
        if (empty($controller)) return $next($request);
        if (str_contains($controller, '.')) $controller = str_replace('.', '\\', $controller);
        $controllerClass = 'app\\admin\\controller\\' . $controller;
        // 类的反射对象
        $classObj        = new ReflectionClass($controllerClass);
        // 类的默认属性
        $properties      = $classObj->getDefaultProperties();
        // 判断是否忽略(如果类中设置了ignoreAuth属性为true，则忽略验证登录)
        $ignoreAuth      = $properties['ignoreAuth'] ?? false;
        // 获取应用
        $appName = app()->http->getName();
        // 获取应用信息
        $adminUserInfo   = session($appName);
        if (!$ignoreAuth) {
            if (empty($adminUserInfo)) {
                return $this->errorJson('请先登录');
            }
            // 判断是否登录过期
            $expireTime = $adminUserInfo['expire_time'];
            if ($expireTime !== true && time() > $expireTime) {
                session($appName, null);
                return $this->errorJson('登录已过期，请重新登录');
            }
        }
        $request->adminUserInfo = $adminUserInfo ?: [];
        return $next($request);
    }
}